package orch

import (
	"github.com/hashicorp/hcl/v2"
	"github.com/ihaiker/tfwrapper/internal/config"
	"github.com/ihaiker/tfwrapper/internal/errors"
	"github.com/ihaiker/tfwrapper/internal/hclfns"
	"github.com/ihaiker/tfwrapper/internal/util"
	"github.com/sirupsen/logrus"
	"os"
	"path"
)

func commandNeedInit(args []string) bool {
	return util.Contain(hclfns.TerraformCommandsNeedInit, args[0])
}

var lastCopyDest string

func copySourceToDest(cfg *config.Wrapper, file *config.StackFileConfig) (string, hcl.Diagnostics) {
	source := path.Dir(cfg.Config.WrapperConfigPath)
	downloadDir := util.SwitchString(file.DownloadDir, cfg.Stack.DownloadDir, cfg.Config.DownloadDir)
	if downloadDir == nil {
		if home, err := os.UserHomeDir(); err != nil {
			return "", errors.Diagnostics("Get user home dir", err)
		} else {
			downloadDir = util.StringPtr(path.Join(home, ".tfwrapper"))
		}
	}
	dest := path.Join(*downloadDir, util.EncodeBase64Sha1(source))
	if lastCopyDest == dest { // 一次运行拷贝一次
		return dest, nil
	}
	logrus.Debugf("use download_dir=%s", dest)
	if err := util.CopyDir(source, dest); err != nil {
		return "", errors.Diagnostics("Copy source dir", err)
	}
	logrus.Debugf("copy source dir %s to %s", source, dest)
	lastCopyDest = dest
	return dest, nil
}
